package com.ts.api.module.channel.entity.bo;

import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.util.reflection.ReflectionUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.ts.api.common.constant.BizEnum;
import com.ts.api.common.constant.channel.ChannelRegisterFieldEnum;
import com.ts.api.exp.BizException;
import com.ts.api.module.channel.entity.ChannelRegisterField;
import com.ts.api.module.channel.entity.po.ChannelUserRegisterPO;
import com.ts.api.module.channel.entity.vo.ReqChannelRegisterFieldVO;
import lombok.Data;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

/**
 * 注册字段业务实体
 */
@Data
public class ChannelRegisterFieldBO {

    /** 转化过后的fieldMap */
    private Map<String, String> fieldMap;

    public ChannelRegisterFieldBO() {
        super();
        fieldMap = MapUtils.newHashMap();
    }

    public ChannelRegisterFieldBO put(String k, String v) {
        fieldMap.put(k, v);
        return this;
    }

    /**
     * 创建业务实体
     *
     * @param  list
     * @return ChannelRegisterFieldBO
     */
    public static ChannelRegisterFieldBO convertField(List<ReqChannelRegisterFieldVO> listReqChannelRegisterVO, List<ChannelRegisterField> listChannelRegisterField) {
        ChannelRegisterFieldBO registerFieldBO = new ChannelRegisterFieldBO();

        Collections.sort(listReqChannelRegisterVO, Comparator.comparing(ReqChannelRegisterFieldVO::getId));
        Collections.sort(listChannelRegisterField, Comparator.comparing(ChannelRegisterField::getId));

        for (int i = 0; i < listReqChannelRegisterVO.size(); i++) {
            ReqChannelRegisterFieldVO registerVO = listReqChannelRegisterVO.get(i);
            ChannelRegisterField registerField = listChannelRegisterField.get(i);
            if (ValidParam.isEmpty(registerVO.getValue())) {
                BizException.fastFail(BizEnum.REGISTER_ERROR_FIELD_VALUE);
            }
            registerFieldBO.put(ChannelRegisterFieldEnum.get(registerField.getName()).getMappingName(), registerVO.getValue());
        }
        return registerFieldBO;
    }

    /**
     * 动态设置参数值
     */
    public void dynamicSetField(ChannelUserRegisterPO userRegister) {
        ReflectionUtils.setFields(userRegister, fieldMap);
    }
}
